var express = require('express');
var fs   = require("fs");
var util = require('util');//util将任意对象转换为字符串的函数
var querystring = require('querystring');
var Article=require("dbHelp");
var router = express.Router();


/* GET home page. */
router.post('/add', function(req, res, next) {
	var _title=req.body.title;
   var _subtitle=req.body.subtitle;
	var _summary=req.body.summary;
	var _content=req.body.content;
    var _imgUrl=req.body.imgUrl;
	var _author=req.body.author;
	var _categoryId='2';

 Article.upsert({
    title: _title,
    summary: _summary,
	content:_content,
	imgUrl:_imgUrl,
	author:_author,
	categoryId:_categoryId,
     subtitle:_subtitle
  }).then(function(test){
	res.send("success");
	});
 
});


/* GET home page. */
router.get('/delete', function(req, res, next) {
	var _id=req.query.id;
	Article.destroy({
	   where:{
		 id:_id
		}
	  }).then(function(user){
		res.send({
                code: 0,
                msg: "删除成功"
            });
	 })
	 
});

/* 获取列表 */
router.get('/getdata', function(req, res, next) {
	//查找第一条
	Article.findAll({where:{categoryId:'2'}}).then(function (articles) {
      var _datas=[];
      for(var i in articles){
        var _obj={
     id: articles[i].dataValues.id,
    title: articles[i].dataValues.title,
    summary:articles[i].dataValues.summary,
	content:articles[i].dataValues.content,
	imgUrl:articles[i].dataValues.imgUrl,
	subtitle:articles[i].dataValues.subtitle,
	createdAt:'2017-08-11'
  //articles[i].dataValues.createdAt
  }
         _datas.push(_obj);
      }
		  res.send(util.inspect(_datas));
      })
});


/*获取某一条数据 */
router.get('/getbyid', function(req, res, next) {
    var _id=req.query.id;
	Article.findById(_id).then(function (article) {
		   var _obj={
            id: article.dataValues.id,
           title: article.dataValues.title,
           summary:article.dataValues.summary,
           content:article.dataValues.content,
           imgUrl:article.dataValues.imgUrl,
           author:article.dataValues.author,
		   subtitle:article.dataValues.subtitle,
           createdAt:'2017-08-11'
       }
        res.send(util.inspect(_obj));
   });

});

  /*修改 */
router.post('/update', function(req, res, next) {
     var _id=req.query.id;
    var _title=req.body.title;
	var _content=req.body.content;
    var _imgUrl=req.body.imgUrl;
	var _subtitle=req.body.subtitle;

	//更改
	Article.update({
		title: _title,
		content:_content,
		imgUrl:_imgUrl,
		subtitle:_subtitle
	  },{where:{
		 id:_id
		}}).then(function (article) {
        res.send({code:0,msg:'修改成功'});
   });
});

module.exports = router;
